package com.tuda.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.tuda.common.annotation.Excel;
import com.tuda.common.core.domain.entity.SysUser;
import com.tuda.common.core.page.TableDataInfo;
import com.tuda.common.enums.OrderPayType;
import com.tuda.common.enums.OrderType;
import com.tuda.common.pay.common.enums.PayTypeEnum;
import com.tuda.common.utils.DateUtils;
import com.tuda.common.utils.ShiroUtils;
import com.tuda.common.utils.ToolUtil;
import com.tuda.system.domain.TudaAppletUser;
import com.tuda.system.domain.TudaOrderTree;
import com.tuda.system.mapper.TudaAppletUserMapper;
import com.tuda.system.mapper.TudaOrderRecordMapper;
import com.tuda.system.mapper.TudaOrderTransferMapper;
import com.tuda.system.model.param.EditOrderOtherFee;
import com.tuda.system.model.param.EditOrderParam;
import com.tuda.system.service.ITudaOrderRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.tuda.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.tuda.system.domain.TudaOrderTransfer;
import com.tuda.system.mapper.TudaOrderMapper;
import com.tuda.system.domain.TudaOrder;
import com.tuda.system.service.ITudaOrderService;
import com.tuda.common.core.text.Convert;

import javax.annotation.Resource;

/**
 * 货运订单Service业务层处理
 *
 * @author tuda
 * @date 2023-07-14
 */
@Service
public class TudaOrderServiceImpl implements ITudaOrderService
{
    @Resource
    private TudaOrderMapper tudaOrderMapper;
    @Resource
    private TudaOrderTransferMapper orderTransferMapper;
    @Resource
    private TudaAppletUserMapper appletUserMapper;
    @Resource
    private TudaOrderTransferMapper tudaOrderTransferMapper;
    @Resource
    private ITudaOrderRecordService orderRecordService;
    @Resource
    private TudaOrderRecordMapper tudaOrderRecordMapper;

    /**
     * 查询货运订单
     *
     * @param id 货运订单主键
     * @return 货运订单
     */
    @Override
    public TudaOrder selectTudaOrderById(Long id)
    {
        return tudaOrderMapper.selectTudaOrderById(id);
    }

    /**
     * 查询货运订单列表
     *
     * @param tudaOrder 货运订单
     * @return 货运订单
     */
    @Override
    public List<TudaOrder> selectTudaOrderList(TudaOrder tudaOrder) {
        SysUser sysUser = ShiroUtils.getSysUser();
        if(ToolUtil.isNotEmpty(sysUser) && sysUser.getUserRole() > 0){
            tudaOrder.setSalesmanPhone(sysUser.getPhonenumber());
            TudaAppletUser appletUser = appletUserMapper.selectTudaAppletUserByPhone(sysUser.getPhonenumber());
            if(ToolUtil.isNotEmpty(appletUser)){
                tudaOrder.setUserId(appletUser.getId());
            }
        }
        if(ToolUtil.isNotEmpty(tudaOrder.getTransitBranch()) || (ToolUtil.isNotEmpty(tudaOrder.getRefund()) && tudaOrder.getRefund() > 0)){
            tudaOrder.setType(1);
        }
        List<TudaOrder> orderList = tudaOrderMapper.selectTudaOrderList(tudaOrder);
        for (TudaOrder order : orderList){
            order.setOrderId(order.getId());
            if(tudaOrder.getType() == 1){
                TudaOrderTransfer tudaOrderTransfer = tudaOrderMapper.queryInfoByValue(order.getId(), tudaOrder.getTransitBranch(), tudaOrder.getRefund());
                if(ToolUtil.isNotEmpty(tudaOrderTransfer)){
                    order.setId(tudaOrderTransfer.getId());
                    order.setOrderTransferId(tudaOrderTransfer.getId());
                    order.setTransitBranch(tudaOrderTransfer.getTransitBranch());
                    order.setTransporter(tudaOrderTransfer.getTransporter());
                    order.setTransporterPhone(tudaOrderTransfer.getTransporterPhone());
                    order.setOwes(tudaOrderTransfer.getOwes());
                    order.setPlateNumber(tudaOrderTransfer.getPlateNumber());
                    order.setAmount(tudaOrderTransfer.getAmount());
                    order.setTransferFee(tudaOrderTransfer.getTransferFee());
                    order.setRefund(tudaOrderTransfer.getRefund() ? 1 : 0);
                    if(tudaOrderTransfer.getRefund()){
                        order.setNotGive(false);
                        order.setNotPay(false);
                    }else {
                        if(tudaOrderTransfer.getOwes().compareTo(new BigDecimal(0.00)) == 1){
                            order.setNotGive(true);
                            order.setNotPay(false);
                        }
                        if(tudaOrderTransfer.getOwes().compareTo(new BigDecimal(0.00)) == -1){
                            order.setNotGive(false);
                            order.setNotPay(true);
                        }
                        if(tudaOrderTransfer.getOwes().compareTo(new BigDecimal(0.00)) == 0){
                            order.setNotGive(false);
                            order.setNotPay(false);
                        }
                    }
                }
            }else {
                order.setNotGive(orderTransferMapper.selectOrderTCount2(order.getOrderId()) > 0 ? true : false);
                order.setNotPay(orderTransferMapper.selectOrderTCount1(order.getOrderId()) > 0 ? true : false);
            }
           TudaAppletUser appletUser= appletUserMapper.selectTudaAppletUserById(order.getUserId());
           if(ToolUtil.isNotEmpty(appletUser)){
               order.setCreateUser(appletUser.getNickName());
           }
           TudaOrder order1 = statistics(order.getOrderId());
           if(ToolUtil.isNotEmpty(order1)){
               order.setCommission(order1.getCommission());
               // 利润（减掉业务员提成）
               order.setProfit(order1.getProfit());
           }
        }
        return orderList;
    }

    @Override
    public List<TudaOrderTree> queryOrderById(String orderIds) {
        List<TudaOrderTree> orderList = tudaOrderMapper.getOrderTree(Convert.toStrArray(orderIds));
        for (TudaOrderTree order : orderList){
            if (ToolUtil.isNotEmpty(order)){
                TudaAppletUser appletUser= appletUserMapper.selectTudaAppletUserById(order.getUserId());
                if(ToolUtil.isNotEmpty(appletUser)){
                    order.setCreateUser(appletUser.getNickName());
                }
            }
        }
        return orderList;
    }

    public List<TudaOrderTransfer> transferList(Long orderId)
    {
        List<TudaOrderTransfer> transferList = orderTransferMapper.queryByInfo(orderId);
        return transferList;
    }



    /**
     * 新增货运订单
     *
     * @param tudaOrder 货运订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTudaOrder(TudaOrder tudaOrder)
    {
        // 获取当前用户ID
        SysUser sysUser = ShiroUtils.getSysUser();
        if(ToolUtil.isNotEmpty(sysUser)){
           TudaAppletUser appletUser = appletUserMapper.selectTudaAppletUserByPhone(sysUser.getPhonenumber());
           if(ToolUtil.isNotEmpty(appletUser)){
               tudaOrder.setUserId(appletUser.getId());
           }
        }
        tudaOrder.setOrderType(OrderType.ORDER_3.getCode());
        tudaOrder.setOrderNum(StringUtils.getOrderNo());
        tudaOrder.setCreateTime(DateUtils.getNowDate());
        if(ToolUtil.isNotEmpty(tudaOrder.getUserName())){
            String[] str = tudaOrder.getUserName().split(",");
            if(str.length > 1){
                tudaOrder.setUserName(str[0]);
                tudaOrder.setSalesmanPhone(str[1]);
            }
        }
        int rows = tudaOrderMapper.insertTudaOrder(tudaOrder);
        if (rows > 0 && (tudaOrder.getPayType().equals(OrderPayType.PAY_TYPE_2.getCode()) || tudaOrder.getPayType().equals(OrderPayType.PAY_TYPE_4.getCode()))){
            orderRecordService.insertOrderRecord(tudaOrder.getId(), OrderPayType.getNameByCode(tudaOrder.getPayType()), tudaOrder.getFreightAmount(),null, null);
        }
        if(tudaOrder.getPaidAmount().compareTo(new BigDecimal(0.00)) == 1){
            orderRecordService.insertOrderRecord(tudaOrder.getId(), "预付款", tudaOrder.getPaidAmount(),null, null);
        }
        insertT(tudaOrder.getId());
        return rows;
    }

    public void insertT(Long orderId){
        int i = 0;
        while (i < 2) {
            i++;
            TudaOrderTransfer tudaOrderTransfer = new TudaOrderTransfer();
            tudaOrderTransfer.setOrderId(orderId);
            tudaOrderTransferMapper.insertTudaOrderTransfer(tudaOrderTransfer);
        }
    }

    /**
     * 修改货运订单
     *
     * @param tudaOrder 货运订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTudaOrder(TudaOrder order)
    {
        if(ToolUtil.isNotEmpty(order) && ToolUtil.isNotEmpty(order.getOrderType()) && order.getOrderType().equals(OrderType.ORDER_4.getCode())){
            order.setUpdateTime(DateUtils.getNowDate());
        }
//        if(ToolUtil.isEmpty(order.getType()) || !order.getType().equals(100)){
//            order.setOrderType(OrderType.ORDER_4.getCode());
//        }
       int rows = 0;
       TudaOrder o = tudaOrderMapper.selectTudaOrderById(order.getId());
        if(ToolUtil.isNotEmpty(o)){
            if(!o.getUserName().equals(order.getUserName())){
                String[] str = order.getUserName().split(",");
                if(str.length > 1){
                    order.setUserName(str[0]);
                    order.setSalesmanPhone(str[1]);
                }
            }
            tudaOrderMapper.deleteTudaOrderTransferByOrderId(order.getId());
            insertTudaOrderTransfer(order);
            rows = tudaOrderMapper.updateTudaOrder(order);
            if(rows > 0)
            if(o.getPayType() != OrderPayType.PAY_TYPE_2.getCode() && o.getPayType() != OrderPayType.PAY_TYPE_4.getCode()){
                if (rows > 0 && (order.getPayType().equals(OrderPayType.PAY_TYPE_2.getCode()) || order.getPayType().equals(OrderPayType.PAY_TYPE_4.getCode()))){
                    orderRecordService.insertOrderRecord(order.getId(), OrderPayType.getNameByCode(order.getPayType()), order.getFreightAmount(),null, null);
                }
                if(order.getPaidAmount().compareTo(new BigDecimal(0.00)) == 1){
                    orderRecordService.insertOrderRecord(order.getId(), "预付款", order.getPaidAmount(),null, null);
                }
            }
        }

        return rows;
    }

    /**
     * 批量删除货运订单
     *
     * @param ids 需要删除的货运订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTudaOrderByIds(String ids)
    {
        tudaOrderMapper.deleteTudaOrderTransferByOrderIds(Convert.toStrArray(ids));
        return tudaOrderMapper.deleteTudaOrderByIds(Convert.toStrArray(ids));
    }

    @Transactional
    @Override
    public int updateStatusByIds(String ids, Integer type) {
        if(ToolUtil.isNotEmpty(type)){
            int num = tudaOrderMapper.updateStatusByIds(Convert.toStrArray(ids));
            if(num > 0) {
                String[] orderIds = ids.split(",");
                for (int i = 0; i < orderIds.length; i++) {
                    tudaOrderRecordMapper.updateRecordType(Long.valueOf(orderIds[i]), 0);
                }
            }
            return num;
        }else {
            int num = tudaOrderMapper.updateTudaOrderByIds(Convert.toStrArray(ids));
            if(num > 0) {
                String[] orderIds = ids.split(",");
                for (int i = 0; i < orderIds.length; i++) {
                    tudaOrderRecordMapper.updateRecordType(Long.valueOf(orderIds[i]), 1);
                }
            }
            return num;
        }
    }

    /**
     * 删除货运订单信息
     *
     * @param id 货运订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTudaOrderById(Long id)
    {
        tudaOrderMapper.deleteTudaOrderTransferByOrderId(id);
        return tudaOrderMapper.deleteTudaOrderById(id);
    }

    @Override
    public int transportSave(EditOrderParam orderTransfer) {
        String[] orderIds = orderTransfer.getIds().split(",");
        for (int i = 0; i < orderIds.length; i++) {
            TudaOrder tudaOrder = tudaOrderMapper.selectTudaOrderById(Long.valueOf(orderIds[i]));
            tudaOrder.setUpdateTime(DateUtils.getNowDate());
            tudaOrder.setOrderType(OrderType.ORDER_4.getCode());
            tudaOrderMapper.deleteTudaOrderTransferByOrderId(tudaOrder.getId());
            insertTudaOrderTransfer(tudaOrder);
            if(tudaOrderMapper.updateTudaOrder(tudaOrder) > 0){
                if(ToolUtil.isNotEmpty(orderTransfer.getAmount())){
                    BigDecimal money = orderTransfer.getAmount().subtract(orderTransfer.getTransferFee());
                    orderTransfer.setOwes(money.setScale(0, BigDecimal.ROUND_HALF_UP));
                }
                orderTransfer.setState(1L);
                orderTransfer.setOrderId(Long.valueOf(orderIds[i]));
                orderTransferMapper.transportSave(orderTransfer);
            }
        }
        return 1;
    }

    @Override
    public int updateOtherFee(EditOrderOtherFee orderFee) {
        if(ToolUtil.isNotEmpty(orderFee)){
            return tudaOrderMapper.updateOrderOtherFee(orderFee.getOrderId(), orderFee.getOtherFee());
        }
        return 0;
    }

    @Override
    public int updateOrderTypeByIds(String ids) {
        if(ToolUtil.isNotEmpty(ids)){
            return tudaOrderMapper.updateOrderTypeByIds(Convert.toStrArray(ids));
        }
        return 0;
    }

    /**
     * 新增货运中转信息
     *
     * @param tudaOrder 货运订单对象
     */
    public void insertTudaOrderTransfer(TudaOrder tudaOrder)
    {
        List<TudaOrderTransfer> tudaOrderTransferList = tudaOrder.getTudaOrderTransferList();
        Long id = tudaOrder.getId();
        if (StringUtils.isNotNull(tudaOrderTransferList))
        {
            List<TudaOrderTransfer> list = new ArrayList<>();
            for (TudaOrderTransfer tudaOrderTransfer : tudaOrderTransferList)
            {
                if(ToolUtil.isNotEmpty(tudaOrderTransfer.getAmount())){
                    BigDecimal money = tudaOrderTransfer.getAmount().subtract(tudaOrderTransfer.getTransferFee());
                    tudaOrderTransfer.setOwes(money.setScale(0, BigDecimal.ROUND_HALF_UP));
                }
                tudaOrderTransfer.setState(1L);
                tudaOrderTransfer.setCreateTime(new Date());
                tudaOrderTransfer.setOrderId(id);
                list.add(tudaOrderTransfer);
            }
            if (list.size() > 0)
            {
                tudaOrderMapper.batchTudaOrderTransfer(list);
            }
        }
    }

    @Override
    public int addOrderTransfer(TudaOrderTransfer tudaOrder) {
        return orderTransferMapper.insertTudaOrderTransfer(tudaOrder);
    }

    public TudaOrder statistics(Long orderId){
        TudaOrder order = tudaOrderMapper.selectTudaOrderById(orderId);
        List<TudaOrderTransfer> transferList = order.getTudaOrderTransferList();
        // 总运费 + 已收费用 = 总收
        BigDecimal amount = order.getFreightAmount().add(order.getPaidAmount());
        // 总收 - 中转费 - （各种费用） = 得到基本费用
        amount = amount.subtract(order.getDrivingFee()).subtract(order.getForkliftFee()).subtract(order.getInspectionFee()).
                subtract(order.getRefuelingFee()).subtract(order.getSmallBoardFee()).subtract(order.getAgencyFee()).subtract(order.getOtherFee()).
                subtract(order.getInsureFee()).subtract(order.getCarWashFee()).subtract(order.getMassLossFee());
        if(ToolUtil.isNotEmpty(transferList) && transferList.size() > 0){
            for(TudaOrderTransfer orderTransfer : transferList){
                // 基本费用 - 司机运费 = 利润
                amount = amount.subtract(orderTransfer.getTransferFee());
            }
            // 利润(没有减掉业务员提成)
            order.setProfit(amount);
            TudaAppletUser user = appletUserMapper.selectTudaAppletUserByPhone(ToolUtil.isNotEmpty(order.getSalesmanPhone()) ? order.getSalesmanPhone() : null);
            if(ToolUtil.isNotEmpty(user)){
                order.setCommission(amount.multiply(user.getPercentage()).divide(new BigDecimal(100)));
                // 利润（减掉业务员提成）
                order.setProfit(order.getProfit().subtract(order.getCommission()));
            }
            tudaOrderMapper.updateTudaOrder(order);
        }
        return order;
    }

}
